
import java.util.*;
import java.net.*;

public class MulticastListener extends Thread {

   public static InetAddress multicastAddr = null;

   private MulticastSocket socket = null;
   public MulticastListener() {
      try {
         multicastAddr = InetAddress.getByName( Darsi.DARSI_MULTI_ADDR );
         socket = new MulticastSocket( Darsi.DARSI_PORT );
      } catch( Exception e ) {
         e.printStackTrace();
      }
   }
   private ArrayList<MulticastCallback> callbacks = new
      ArrayList<MulticastCallback>();
   public void addCallback( MulticastCallback callback ) {
      callbacks.add( callback );
   }
   private void sendToCallbacks( DatagramPacket packet ) {
      String msg = new String(packet.getData()).trim();
      Event event = null;
      if( msg.equals( "TIMER" ) ) {
         event = new Event( Event.EVENT_OTHER_HOST_TIMER );
      } else {
         try {
            String[] voteParams = msg.split( "," );
            event = new Event( InetAddress.getByName(voteParams[0]),
                  Integer.parseInt(voteParams[1]), Event.EVENT_VOTE );
         } catch ( Exception e ) {
            e.printStackTrace();
         }
      }
      if( event != null ) {
         for( int i=0; i<callbacks.size(); i++ ) {
            callbacks.get(i).handleIncoming( event );
         }
      }
   }
   public void send( String msg ) {
      byte[] buffer = msg.getBytes();
      DatagramPacket toSend = new DatagramPacket( buffer, buffer.length,
            multicastAddr, Darsi.DARSI_PORT );
      try {
         socket.send( toSend );
      } catch ( Exception e ) {
         e.printStackTrace();
      }
   }
   public void run() {
      try {
         socket.joinGroup( multicastAddr );
      } catch ( Exception e ) {
         e.printStackTrace();
      }
      while( true ) {
         try {
            byte[] buffer = new byte[65535];
            DatagramPacket packet = new DatagramPacket( buffer, buffer.length,
                  multicastAddr, Darsi.DARSI_PORT );
            socket.receive( packet );
            sendToCallbacks( packet );
         } catch ( Exception e ) {
            e.printStackTrace();
         }
      }
   }

   public static void main( String[] args ) {
      MulticastListener listener = new MulticastListener( );
      listener.addCallback( new MulticastCallback() {
         public void handleIncoming( Event event ) {
            System.out.println( event );
         }
      });
      listener.start();
   }
}
